﻿using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace GetIPAddress.Frontend
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //1.
            GetPrivateIP();

            //2.
            Console.WriteLine("http://checkip.dyndns.org/ : " + GetPublicIP());
            Console.WriteLine();

            //3.
            Console.WriteLine("http://getipaddress.azurewebsites.net/ : " + GetIPAddress());
            Console.WriteLine();
        }

        private static void GetPrivateIP()
        {
            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                foreach (var unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
                    if (unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Console.WriteLine(networkInterface.Name);
                        Console.WriteLine(unicastAddress.Address.ToString());
                        Console.WriteLine();
                    }
        }

        private static string GetPublicIP()
        {
            string address;
            var webRequest = WebRequest.Create("http://checkip.dyndns.org/");
            using (var webResponse = webRequest.GetResponse())
            using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
                address = streamReader.ReadToEnd();

            int startIndex = address.IndexOf("Address: ") + 9;
            int lastIndex = address.LastIndexOf("</body>");
            address = address.Substring(startIndex, lastIndex - startIndex);

            return address;
        }

        private static string GetIPAddress()
        {
            string address;
            var webRequest = WebRequest.Create("http://getipaddress.azurewebsites.net/");
            using (var webResponse = webRequest.GetResponse())
            using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
                address = streamReader.ReadToEnd();

            int startIndex = address.IndexOf("<ip>") + 4;
            int lastIndex = address.LastIndexOf("</ip>");
            address = address.Substring(startIndex, lastIndex - startIndex);

            return address;
        }
    }
}